package com.sunnyatwal.kettlebell.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;

import com.sunnyatwal.kettlebell.R;

public class Exercise implements Parcelable{
    
	private int icon = R.drawable.ic_launcher;
    private String title;
    private List<ExerciseUnit> routine;
    private int remainingTotalTime = 0;
    private int currentSubExerciseIndex = 0;
	private boolean mIsFinished = false;
    private static final String TAG = "Exercise";
    
    public Exercise(){
    }
    
    public Exercise(String title, ArrayList<ExerciseUnit> routine) {
        this.title = title;
        this.routine = routine;
    }
    
    public Exercise(String title) {
        this.title = title;
        this.routine = new ArrayList<ExerciseUnit>();
    }
    
    public Exercise(Parcel p) {
    	icon = p.readInt();
    	title = p.readString();
    	remainingTotalTime = p.readInt();
    	currentSubExerciseIndex = p.readInt();
    	mIsFinished = p.readByte() == 1;
    	
    	routine = new ArrayList<ExerciseUnit>();
    	Parcelable[] asArray = p.readParcelableArray(ExerciseUnit.class.getClassLoader());
    	for (Parcelable i : asArray) {
    		routine.add((ExerciseUnit) i);
		}
    	
    }
    

    public static final Parcelable.Creator<Exercise> CREATOR = 
    		new Parcelable.Creator<Exercise>() {
				@Override
				public Exercise createFromParcel(Parcel source) {
					return new Exercise(source);
				}

				@Override
				public Exercise[] newArray(int size) {
					return new Exercise[size];
				}
    };	
        
	@Override
	public int describeContents() {
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {		
		dest.writeInt(icon);
		dest.writeString(title);
		dest.writeInt(remainingTotalTime);
		dest.writeInt(currentSubExerciseIndex);
		dest.writeByte((byte) (mIsFinished ? 1 : 0));
		
		ExerciseUnit[] asArray = routine.toArray(new ExerciseUnit[routine.size()]);
		dest.writeParcelableArray(asArray, flags);		
	}
    
    public int getIcon() {
    	return icon;
    }
    
    public void setTitle(String title) {
    	this.title = title;
    }
    
    public String getTitle() {
    	return title;
    }
    
    public void setRoutine(List<ExerciseUnit> list) {
    	this.routine = new ArrayList<ExerciseUnit>(list);
    }
        
    public List<ExerciseUnit> getRoutine() {
    	return routine;
    }
    
    public ExerciseUnit getRoutineItem(int i) {
    	return routine.get(i);
    }
    
    public boolean setRoutineItem(int i, ExerciseUnit entry) {
    	routine.set(i, entry);
    	return true;
    }
    
    public boolean AddRoutineItem(ExerciseUnit entry) {
    	return routine.add(entry);
    }
    
    public boolean InsertRoutineItem(int index, ExerciseUnit entry) {
    	try {
    		routine.add(index, entry);
    	}
    	catch (Exception e) {    		
    		return false;
    	}
    	
    	return true;
    }
    
    public ExerciseUnit RemoveRoutineItem(int i) {
    	ExerciseUnit e = routine.remove(i);
    	return e;
    }
    
    public int getRemainingTime() {
    	
    	int total = 0;
    	for (int i = 0; i < routine.size(); i++)
    		if(!(routine.get(i) instanceof CountDown))
    			total += routine.get(i).getRemainingTime();
    	
    	return total;
    }
    
    public int getRemainingTimeCurrentExercise() {
    	return routine.get(currentSubExerciseIndex).getRemainingTime();
    }
    
    private String getTimePretty(int time)
	{
		int milli = time % 1000;
		int seconds = (time / 1000) % 60;
		int minutes = (time / 1000) / 60;
		
		if (milli > 0)
			seconds++;
		
		String strSeconds = Integer.toString(seconds);
		String strMinutes = Integer.toString(minutes);
		
		strSeconds = strSeconds.length() < 2 ? "0" + strSeconds : strSeconds;
		strMinutes = strMinutes.length() < 2 ? "0" + strMinutes : strMinutes;
		
		return new String(strMinutes + ":" + strSeconds);	
	}
    
    public String getRemainingTimePretty(boolean showTitle) {
    	String strRet = showTitle ? "Tot: " : "";
    	strRet += getTimePretty(getRemainingTime());
    	return strRet;
    }
    
    public int getNumExercisesInRoutine() {
    	return routine.size();
    }
    
	public int getTotalTime() {
		
		int total = 0;
    	try
    	{
    	for (Iterator<ExerciseUnit> i = routine.iterator(); i.hasNext();)
    	{
    		ExerciseUnit e = i.next();
    		if(!(e instanceof CountDown))
    			total += e.getTotalTime();
    	}
    	
    	return total;
    	}
    	catch(Exception e) {
    		Log.e(TAG, "Exercise has total time of 0");
    		return 0;
    	}
	}
	
	public ElapsedTimeResult ElapseTime(int pCountDownInterval)
	{
		ExerciseUnit e = routine.get(currentSubExerciseIndex);
	 
		ElapsedTimeResult result = e.ElapseTime(pCountDownInterval);
		
		if (result.getIsFinished())
		{
			if (currentSubExerciseIndex < routine.size() - 1)
				currentSubExerciseIndex++;
			else
			{
				setIsFinished(true);
				return new ElapsedTimeResult(result.getExtra(), true);				
			}
		}
		
		return new ElapsedTimeResult(result.getExtra(), false);
	}
	
	public ExerciseUnit getCurrentExercise() throws Exception
	{
		return routine.get(currentSubExerciseIndex);
	}

	public boolean isFinished() {
		return mIsFinished;
	}
	
	public void setIsFinished(boolean isFinished) {
		mIsFinished = isFinished;
	}
	
	public String getPrettyListMainText() {
		
		try {
			return getCurrentExercise().getPrettyListMainText();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String getPrettyListSubText() {
		
		try {
			return getCurrentExercise().getPrettyListSubText();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String getPrettyNotificationMainText() 
	{	
		try {
			return getCurrentExercise().getPrettyNotificationMainText();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String getPrettyNotificationSubText() 
	{	
		try {
			return getRemainingTimePretty(true) + "\t\t" + getCurrentExercise().getPrettyNotificationSubText();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void insertCountDownAtCurrentIndex() {
		
		if(routine.get(currentSubExerciseIndex) instanceof CountDown)
			routine.set(currentSubExerciseIndex, new CountDown());
		else		
			routine.add(currentSubExerciseIndex, new CountDown());
	}
	
	public int checkForTimerBeeps() {
		
		int rTime = routine.get(currentSubExerciseIndex).getRemainingTime();
		final int cTime = routine.get(currentSubExerciseIndex).getCurrentTime();
		
		if (isFinished()) {
			return 4;
		}
		else if (rTime == 3000) {
			return 3;
		} else if (rTime == 2000) {
			return 2;
		} else if (rTime == 1000) {
			return 1;
		} else if (cTime == 0) {
			return 0;
		}
		
		return -1;		
	}
	
	public boolean isEqual(Exercise e) {
		return this.title.equalsIgnoreCase(e.title);
	}
	
	public boolean isTitleEqual(String title) {
		return this.title.equalsIgnoreCase(title);
	}

	public int getCurrentTimeCurrentExercise() {
		return routine.get(currentSubExerciseIndex).getCurrentTime();
	}

}